<?php

namespace App\Http\Middleware;

use Illuminate\Auth\AuthenticationException;
use App\Exceptions\ExceptionApi;
use App\Models\User;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Closure;

class Authenticate extends Middleware
{
    /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Auth\AuthManager
     */
//    protected $auth;

    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws ExceptionApi
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authVerify($request, $guards);
        return $next($request);
    }

    /**
     * 权限验证
     * @return void|User
     * @throws ExceptionApi
     * @throws AuthenticationException
     */
    protected function authVerify(Request $request, array $guards)
    {
        if (empty($guards)) {
            $guards = [null];
        }
        foreach ($guards as $guard) {
            if($guard=='api'){
                $apiToken = $request->input('token');
                if(!$apiToken){
                    throw new ExceptionApi('请登录后再操作');
                }
                $user = User::findByApiToken($apiToken);
                $request->user = $user;
                return $user;
            }
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        throw new AuthenticationException(
            'Unauthenticated.', $guards, $this->redirectTo($request)
        );

    }

//    protected function redirectTo($request):string
//    {
//        return route('login');
//    }

}
